/** biome-ignore-all lint/a11y/noStaticElementInteractions: false positive */
/** biome-ignore-all lint/a11y/useKeyWithClickEvents: false positive */
import { cn } from "@renderer/lib/utils";
import { X } from "lucide-react";
import type { ReactNode } from "react";
import { useEffect, useState } from "react";
import { Button } from "./base/button";

const sizes = {
  xs: "sm:max-w-xs",
  sm: "sm:max-w-sm",
  md: "sm:max-w-md",
  lg: "sm:max-w-lg",
  xl: "sm:max-w-xl",
  "2xl": "sm:max-w-2xl",
  "3xl": "sm:max-w-3xl",
  "4xl": "sm:max-w-4xl",
  "5xl": "sm:max-w-5xl",
};

interface OverlayProps {
  isVisible: boolean;
  size?: keyof typeof sizes;
  isBlurred?: boolean;
  className?: string;
  children: ReactNode;
  onClose?: () => void;
}

export function Overlay({
  isVisible,
  size = "lg",
  isBlurred = true,
  className,
  children,
  onClose,
}: OverlayProps) {
  const [isClosing, setIsClosing] = useState(false);
  const [shouldRender, setShouldRender] = useState(isVisible);

  // Handle opening animation
  useEffect(() => {
    if (isVisible) {
      setShouldRender(true);
      setIsClosing(false);
    }
  }, [isVisible]);

  // Handle closing animation
  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (!isVisible && shouldRender) {
      setIsClosing(true);
      // Wait for animation to complete before removing from DOM
      timer = setTimeout(() => {
        setShouldRender(false);
        setIsClosing(false);
      }, 300); // Match animation duration
    }

    return () => {
      clearTimeout(timer);
    };
  }, [isVisible, shouldRender]);

  useEffect(() => {
    if (!shouldRender || !onClose) return;

    const handleEscapeKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        onClose();
      }
    };

    document.addEventListener("keydown", handleEscapeKey);
    return () => {
      document.removeEventListener("keydown", handleEscapeKey);
    };
  }, [shouldRender, onClose]);

  if (!shouldRender) return null;

  const handleBackdropClick = () => {
    onClose?.();
  };

  const handleContentClick = (e: React.MouseEvent) => {
    e.stopPropagation();
  };

  return (
    <div
      className={cn(
        "pointer-events-auto fixed inset-0 z-50 h-screen",
        isBlurred && "bg-black/15 backdrop-blur-[1px] backdrop-filter",
        // Background fade animation
        !isClosing
          ? "fade-in animate-in duration-300"
          : "fade-out animate-out duration-300",
      )}
      onClick={handleBackdropClick}
    >
      <div className="grid h-full grid-rows-[1fr_auto] justify-items-center sm:grid-rows-[1fr_auto_1fr] md:p-4">
        <div
          className={cn(
            "row-start-2 w-full cursor-auto text-left align-middle",
            "relative bg-overlay text-overlay-fg",
            "shadow-lg ring ring-fg/5 dark:ring-border",
            "rounded-t-2xl md:rounded-xl",
            // Content animation - entrance
            !isClosing && [
              "slide-in-from-bottom animate-in duration-300 ease-out",
              "md:fade-in md:zoom-in-95 md:slide-in-from-bottom-0",
            ],
            // Content animation - exit
            isClosing && [
              "slide-out-to-bottom animate-out duration-300 ease-in",
              "md:fade-out md:zoom-out-95 md:slide-out-to-bottom-0",
            ],
            sizes[size],
            className,
          )}
          onClick={handleContentClick}
        >
          {children}
          {onClose && (
            <Button
              intent="plain"
              size="sq-xs"
              onPress={onClose}
              className="absolute top-4 right-4 z-10 rounded-md p-1 text-muted-fg hover:bg-secondary hover:text-fg"
            >
              <X className="size-4" />
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}
